﻿using Outlook = Microsoft.Office.Interop.Outlook;
using Manager = OMC.DataManagement.Manager;
using System.Diagnostics;
using System;
using System.IO;
using OMC.AddInHandling;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using System.Configuration;
using Logger = Microsoft.Practices.EnterpriseLibrary.Logging.Logger;
using System.Collections.Specialized;
using OMC.Utils;
using Office = Microsoft.Office.Core;
using System.Collections.Generic;

namespace OMC
{
    /// <summary>
    /// The main class contains the init, the start sequence and the destroy
    /// methods of the application. This class makes the application runnable.
    /// </summary>
    public partial class Main
    {
        private Manager Manager { get; set; }
        private AddInHandler AddInHandler { get; set; }
        private Ribbon ribbon;


        /// <summary>
        /// The application data path.
        /// </summary>
        public static String ApplicationDataPath { get; private set; }

        public static ICollection<string> LogFilePaths { get; private set; }

        /// <summary>
        /// Returns the OMC ribbon.
        /// </summary>
        /// <returns>The OMC ribbon</returns>
        protected override Office.IRibbonExtensibility CreateRibbonExtensibilityObject()
        {
            ribbon = new Ribbon();
            return ribbon;
        }


        /// <summary>
        /// This method initialize a manager and the handler of the application.
        /// </summary>
        /// <remarks>
        /// Source: http://msdn.microsoft.com/en-us/library/ms268750
        /// </remarks>
        private void Init()
        {
            InitLogging();
            Logger.Write("Initializing");

            try
            {
                //Initialize manager
                Outlook.Explorer explorer = Application.Explorers.Application.ActiveExplorer();
                Outlook.Stores stores = explorer.Session.Stores;
                Outlook.NameSpace nameSpace = explorer.Application.GetNamespace("MAPI");
                Manager = new Manager(stores, nameSpace, false);
                ribbon.Manager = Manager;
                AddInHandler = new AddInHandler(stores, Manager);

                //Initialize handler
                Application.ItemContextMenuDisplay
                    += new Outlook.ApplicationEvents_11_ItemContextMenuDisplayEventHandler(
                    AddInHandler.contextMenuDisplay);
            }
            catch (Exception ex)
            {
                LoggerUtils.Write("It isn't possible to init OMC Plugin", ex, TraceEventType.Critical);
            }
        }

        /// <summary>
        /// Init logging framework, i.e. set the logging path.
        /// The logging path is set by replacing
        ///     ###ApplicationDatan###
        /// by the path to the application data directory in the logging configuration.
        /// </summary>
        private static void InitLogging()
        {
            LogFilePaths = new List<string>();

            // The solution below only replaces ###ApplicationData### in the logging configuration.
            // It only replaces the pattern in the field FileName of RollingFlatTraceListener.
            //
            // A more general and better solution would be to replace patterns like ###ApplicationData### in all fields of App.config.
            ApplicationDataPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), "Outlook Mail Classifier");
            Directory.CreateDirectory(ApplicationDataPath);

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            LoggingSettings loggingSection = (LoggingSettings)config.GetSection("loggingConfiguration");
            foreach (TraceListenerData traceListener in loggingSection.TraceListeners)
            {
                if (traceListener is RollingFlatFileTraceListenerData)
                {
                    RollingFlatFileTraceListenerData rollingFlatTraceListener = (RollingFlatFileTraceListenerData)traceListener;
                    if (rollingFlatTraceListener.FileName.Contains("###ApplicationData###"))
                    {
                        rollingFlatTraceListener.FileName = rollingFlatTraceListener.FileName.Replace("###ApplicationData###", ApplicationDataPath);
                    }
                    LogFilePaths.Add(rollingFlatTraceListener.FileName);
                }
            }
            config.Save();
        }

        /// <summary>
        /// This Method cleans up before the application goes down.
        /// </summary>
        private void CleanUp()
        {
            try
            {
                //remove Handler
                Application.ItemContextMenuDisplay
                    -= new Outlook.ApplicationEvents_11_ItemContextMenuDisplayEventHandler(
                    AddInHandler.contextMenuDisplay);
                Logger.Write("Cleaned Up");
            }
            catch (Exception ex)
            {
                String message = "It isn't possible to clean up OMC Plugin";
                LoggerUtils.Write(message, ex, TraceEventType.Critical);
            }
        }

        #region Startup,Shutdown
        private void main_Startup(object sender, System.EventArgs e)
        {
            Init();
        }

        private void main_Shutdown(object sender, System.EventArgs e)
        {
            CleanUp();
        }
        #endregion

        #region VSTO generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(main_Startup);
            this.Shutdown += new System.EventHandler(main_Shutdown);
        }
        #endregion
    }
}